package controllers;

import java.util.List;

import models.Business;

import org.apache.commons.lang.StringUtils;

import play.data.binding.As;
import play.data.validation.Required;

public class BusinessController extends BaseController{

    public static void list(String name) {
        if (StringUtils.isBlank(name)) {
            List<Business> businesses = Business.findAll();
            render("/business/list.html", businesses, name); 
        }
        List<Business> businesses = Business.find("name like '%" + name + "%'").fetch();
        render("/business/list.html", businesses, name);
    }
    
    
    public static void save(@Required(message = "business.name.require") String name, @As(value="true") boolean isActive) {
        if (validation.hasErrors()) {
            params.flash();
            validation.keep();
            form(null);
        }
        Business business = new Business();
        setBusinessValue(business, name, isActive).save();
        form(business.id);
    }
    
    public static void update(Long businessId, @Required(message = "business.name.require") String name, @As(value="true") boolean isActive) {
        if (validation.hasErrors()) {
            params.flash();
            validation.keep();
            form(businessId);
        }
        Business business = Business.findById(businessId);
        if (business == null) {
            notFound();
        }
      
        setBusinessValue(business, name, isActive).save();
        form(business.id);
    }
    
    private static Business setBusinessValue(Business business, String name, boolean isActive) {
        business.name = name;
        business.isActive = isActive;
        return business;
    }
    
    public static void form(Long businessId) {
        if (businessId == null) {
            render("/business/form.html");
        }
        Business business = Business.findById(businessId);
        if (business == null) {
            notFound();
        }
        render("/business/form.html", business);
    }
    
    
}
